package DFS;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Classname 全排列47
 * @Description TODO
 * @Date 2023/3/6 21:15
 * @Created by xjl
 */
public class 全排列47 {

    @Test
    public void test(){
        List<List<Integer>> lists = listuteUnique(new int[]{1, 2, 2, 3});
        for (List<Integer> list:lists){
            for (int i:list){
                System.out.println(i);
            }
        }
    }

    public List<List<Integer>> listuteUnique(int[] nums) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        boolean [] visit = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, lists, 0, list,visit);
        return lists;
    }
    public void dfs(int[] nums, List<List<Integer>> lists, int idx, List<Integer> list,boolean[] visit) {
        if (idx == nums.length) {
            lists.add(new ArrayList<Integer>(list));
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (visit[i] || (i > 0 && nums[i] == nums[i - 1] && !visit[i - 1])) {
                continue;
            }
            list.add(nums[i]);
            visit[i] = true;
            dfs(nums, lists, idx + 1, list,visit);
            // 回溯算法
            visit[i] = false;
            list.remove(idx);
        }
    }
}
